﻿<template>
	<div class="sysDbLink-container">
		<el-dialog v-model="state.isShowDialog" :width="600" draggable="" :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit /> </el-icon>
					<span>{{ props.title }}</span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="state.ruleForm.id" />
					</el-form-item>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="连接驱动" prop="dbType" :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
							<el-select v-model="state.ruleForm.dbType" filterable clearable class="w100" @change="onChange">
								<el-option v-for="item in state.dBTypeList" :key="item.value" :label="item.value" :value="item.code" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="连接名称" prop="name" :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.name" placeholder="请输入连接名称" maxlength="200" show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="主机地址" prop="host" :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.host" placeholder="请输入主机地址" maxlength="50" show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="端口" prop="port" :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.port" placeholder="请输入端口" maxlength="50" show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="用户" prop="userName" :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.userName" placeholder="请输入用户" maxlength="50" show-word-limit
								clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="密码" prop="password" :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.password" placeholder="请输入密码" maxlength="50" show-word-limit clearable
								type="password" show-password />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20"
						v-if="['MySQL', 'SQLServer', 'PostgreSQL', 'KingbaseES'].includes(state.ruleForm.dbType)">
						<el-form-item label="库名" prop="serviceName" v-if="state.ruleForm.dbType === 'MySQL'">
							<el-input v-model="state.ruleForm.serviceName" placeholder="请输入库名" maxlength="50" show-word-limit
								clearable>
								<template #append>
									<span class="cursor-pointer" @click="test()" v-loading="state.testLoading">连接测试</span>
								</template>
							</el-input>
						</el-form-item>
						<el-form-item label="库名" prop="serviceName" v-else>
							<el-input v-model="state.ruleForm.serviceName" placeholder="请输入库名" maxlength="50" show-word-limit
								clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20"
						v-if="state.ruleForm.dbType && state.ruleForm.dbType !== 'MySQL'">
						<el-form-item label="模式" prop="dbSchema">
							<el-input v-model="state.ruleForm.dbSchema"
								:placeholder="state.ruleForm.dbType === 'Oracle' || state.ruleForm.dbType === 'DM' ? '与用户同名' : ''"
								maxlength="50" show-word-limit clearable :disabled="state.ruleForm.dbType !== 'KingbaseES'">
								<template #append>
									<span class="cursor-pointer" @click="test()" v-loading="state.testLoading">连接测试</span>
								</template>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" v-if="state.ruleForm.dbType === 'Oracle'">
						<el-form-item label="更多" prop="oracleExtend">
							<el-switch v-model="state.ruleForm.oracleExtend" :active-value="1" :inactive-value="0" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20"
						v-if="state.ruleForm.dbType === 'Oracle' && !!state.ruleForm.oracleExtend">
						<el-form-item label="连接方式" prop="oracleLinkType">
							<el-select v-model="state.ruleForm.oracleLinkType" filterable clearable class="w100">
								<el-option v-for="item in state.oracleLinkTypeOptions" :key="item.fullName" :label="item.fullName"
									:value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20"
						v-if="state.ruleForm.dbType === 'Oracle' && !!state.ruleForm.oracleExtend">
						<el-form-item label="角色" prop="oracleRole">
							<el-select v-model="state.ruleForm.oracleRole" filterable clearable class="w100">
								<el-option v-for="item in state.oracleRoleOptions" :key="item.fullName" :label="item.fullName"
									:value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20"
						v-if="state.ruleForm.dbType === 'Oracle' && !!state.ruleForm.oracleExtend">
						<el-form-item label="服务名" prop="oracleService">
							<el-input v-model="state.ruleForm.oracleService" placeholder="请输入服务名" maxlength="50" show-word-limit
								clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="备注" prop="remark">
							<el-input v-model="state.ruleForm.remark" placeholder="请输入备注" maxlength="500" show-word-limit clearable />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { ElMessage } from "element-plus";
import type { FormRules } from "element-plus";
import { getAPI } from '/@/utils/axios-utils';
import { SysDictDataApi } from '/@/api-services/api';
import { updateSysDbLink, addSysDbLink, detailSysDbLink, testDbConnection } from '/@/api/system/sysDbLink';

import { formatDate } from '/@/utils/formatTime';

//父级传递来的参数
var props = defineProps({
	title: {
		type: String,
		default: "",
	},
});
//父级传递来的函数，用于回调
const emit = defineEmits(["reloadTable"]);
const ruleFormRef = ref();
const state = reactive({
	isShowDialog: false,
	testLoading: false,
	ruleForm: {
		id: '',
		name: '',
		host: '',
		dbType: '',
		port: '',
		userName: '',
		password: '',
		serviceName: '',
		dbSchema: '',
		remark: '',
		oracleExtend: 0,
		oracleRole: '',
		oracleLinkType: '',
		oracleService: ''
	},
	dBTypeList: [] as any,
	oracleLinkTypeOptions: [
		{ fullName: 'SERVICE', id: 'SERVICE' },
		{ fullName: 'SID', id: 'SID' },
		{ fullName: 'SCHEMA', id: 'SCHEMA' },
		{ fullName: 'TNS', id: 'TNS' },
	],
	oracleRoleOptions: [
		{ fullName: 'Default', id: 'Default' },
		{ fullName: 'SYSDBA', id: 'SYSDBA' },
		{ fullName: 'SYSOPER', id: 'SYSOPER' },
	],
});

//自行添加其他规则
const rules = ref<FormRules>({
});

// 页面加载时
onMounted(async () => {
	let resDicData = await getAPI(SysDictDataApi).apiSysDictDataDataListCodeGet('dbType');
	state.dBTypeList = resDicData.data.result;
});

const onChange = (e: any) => {
	state.ruleForm.dbType = e;
	let port = '';
	let dbSchema = '';
	switch (e) {
		case 'SQLServer':
			port = '1433';
			dbSchema = 'dbo';
			break;
		case 'MySQL':
			port = '3306';
			break;
		case 'Oracle':
			port = '1521';
			break;
		case 'DM':
			port = '5236';
			break;
		case 'KingbaseES':
			port = '54321';
			dbSchema = 'public';
			break;
		case 'PostgreSQL':
			port = '5432';
			dbSchema = 'public';
			break;
		default:
			port = '';
			break;
	}
	state.ruleForm.dbSchema = dbSchema;
	state.ruleForm.port = port;
};

const onOracleLinkTypeChange = (e: any) => {
	state.ruleForm.oracleLinkType = e;
	// setFieldsValue({ port, dbSchema });
	// clearValidate();
}

// 打开弹窗
const openDialog = async (row: any) => {
	let rowData = JSON.parse(JSON.stringify(row));
	if (rowData.id)
		state.ruleForm = (await detailSysDbLink(rowData.id)).data.result;
	else
		state.ruleForm = rowData;
	state.isShowDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
	emit("reloadTable");
	state.isShowDialog = false;
};

// 取消
const cancel = () => {
	state.isShowDialog = false;
};

// 提交
const submit = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			let values = state.ruleForm;
			if (state.ruleForm.id == undefined || state.ruleForm.id == null || state.ruleForm.id == "" || state.ruleForm.id == 0) {
				await addSysDbLink(state.ruleForm);
			} else {
				await updateSysDbLink(state.ruleForm);
			}
			closeDialog();
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: "error",
			});
		}
	});
};

const test = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			state.testLoading = true;
			state.ruleForm.oracleExtend = !!state.ruleForm.oracleExtend;
			const query = {
				...state.ruleForm,
				id: state.ruleForm.id,
			};
			testDbConnection(query)
				.then(res => {
					ElMessage.success(res.msg || '连接成功！');
					state.testLoading = false;
				})
				.catch(() => {
					state.testLoading = false;
				});
		}
	})
}






//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
